package com.EthanYankang;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @Author: Ethan Yankang
 * @Program: my-tomcat2
 * @Date: 2024-09-09 13:33
 **/
public class SocketProcess implements Runnable {
    private Socket socket;
    private Request request;
    private Response response;
    static int begin=0;
    static int i=0;

    public SocketProcess(Socket socket) {
        this.socket=socket;
    }

    @Override
    public void run() {
       try {
           processSocket(socket);
           System.out.println("建立第一"+(++i)+"次连接");
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
    }

    private void processSocket(Socket socket) {
        //    处理socket连接——>读数据、写数据。
        //    因为浏览器里面就是http请求(一种数据规范)，所以就是读取并解析以这种规范呈现的数据
        try {
            InputStream inputStream=socket.getInputStream();//从套接字拉取数据流。
            byte[] bytes=new byte[1024];
            inputStream.read(bytes);//将拉取来的数据流存在字节数组里面
            //printHttpContent(bytes);//以文本形式展示报文
            //printHttpContentAsBinary(bytes);//以二进制01展示报文
            //System.out.println(getRequestMethod(bytes,begin));//打印获取到的请求方法
            //System.out.println(getRequestURL(bytes,begin));//打印获取到的请求路径
            //System.out.println(getRequestProtocol(bytes,begin));//打印获取到的请求协议
            //解析http报文，封装成request请求传入servlet中去。
            request=new Request(socket,getRequestMethod(bytes,begin),getRequestURL(bytes,begin),getRequestProtocol(bytes,begin));
            MyServlet myServlet=new MyServlet();
            response = new Response(request);
            myServlet.service(request,response);//正常调用servlet方法

            //现在这里的servlet不用自己创建了，直接将编译后的放在了webapps下面了，作为应用，供访问

            //真正发送响应
            response.complete();



        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }

    private String getRequestProtocol(byte[] bytes, int begin) {
        //System.out.println("对应请求协议：");
        int pos=begin;
        StringBuilder protocol = new StringBuilder();
        for (; pos < bytes.length; pos++){
            if (bytes[pos] == '\r') {
                pos+=2;
                this.begin=pos;
                break;
            }
            protocol.append((char)bytes[pos]);
        }
        return protocol.toString();
    }

    private String getRequestURL(byte[] bytes, int begin) {
        //System.out.println("对应请求路径：");
        int pos=begin;
        StringBuilder url = new StringBuilder();
        for (; pos < bytes.length; pos++) {
            if (bytes[pos] == ' ') {
              this.begin=++pos;
                break;
            }
            url.append((char)bytes[pos]);
        }
        return url.toString();
    }

    private String getRequestMethod(byte[] bytes,int begin) {
        //System.out.println("对应请求方法：");
        int pos=begin;
        StringBuilder method = new StringBuilder();
        for (; pos < bytes.length; pos++) {
            if (bytes[pos] == ' ') {
                this.begin=++pos;
                break;
            }
            method.append((char)bytes[pos]);
        }
        return method.toString();
    }


    private void printHttpContent(byte[] bytes) {
        System.out.println("报文：\n");
        for (int i = 0; i < bytes.length; i++) {
            System.out.print((char)bytes[i]);
        }
        System.out.println("以上是全部的请求文本，亦称——报文\n\n");

    }

    private void printHttpContentAsBinary(byte[] bytes){
     System.out.println("对应的二进制字节流:");
                for (int i = 0; i < bytes.length; i++) {
        System.out.print(String.format("%8s", Integer.toBinaryString(bytes[i] & 0xFF)).replace(' ', '0') );
        if ((i+1)%25==0)
            System.out.println();
        }
        System.out.println("\n\n");
    }
}
